package com.haidechizi.i18n.common.execute.wapper;

import com.haidechizi.i18n.common.config.Configuration;
import com.haidechizi.i18n.common.execute.AbstractTranslateExecute;
import com.haidechizi.i18n.common.execute.TranslateExecute;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.annotation.Order;

/**
 * 国际化执行器代理类，支持选择国际化的策略
 * <p>
 * 支持动态配置，可以动态修改国际化的策略
 */
@Slf4j
@Order(10)
public class TranslateExecuteProxy implements TranslateExecute, ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private Configuration configuration;
    private TranslateExecute translateExecute;

    /**
     * 动态更改策略接口
     *
     * @param value
     */
    public void changeTranslateExecuteName(String value) {
        configuration.setStrategyName(value);
        log.info("动态切换国际化策略,{}", value);
        refreshTranslateExecute();
    }

    @Override
    public void assembleI18nInfo(Object model) {
        translateExecute.assembleI18nInfo(model);
    }

    @Override
    public String name() {
        throw new UnsupportedOperationException("不支持");
    }

    /**
     * 设置或者动态刷新国际化策略
     */
    private void refreshTranslateExecute() {
        translateExecute = AbstractTranslateExecute.getTranslateExecute(configuration.getStrategyName());
    }

    /**
     * 设置国际化的策略
     * <p>
     * 在spring初始化完成后，设置国际化策略
     *
     * @param contextRefreshedEvent
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        refreshTranslateExecute();
    }
}
